package com.dchh.android.suverynew.act;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.PhotoGridAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.common.ZoomImagePoup;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.ImageInfoBean;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.db.Sqlite.RecordDBManager;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.PhotoUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 样方图纸拍摄
 *
 * @author zhoudan
 * @date 2016年5月6日
 */
public class YFTZPhotoActivity extends SBaseActivity {

    private RelativeLayout main;

    private TextView title;
    private GridView gridView;
    private LinearLayout camera;
    private ToggleButton btn;
    private LinearLayout positionLayout;
    private EditText position;
    private Button saveBtn;

    private List<ImageInfoBean> imageInfoList = new ArrayList<ImageInfoBean>();
    private PhotoGridAdapter adapter;

    // 相关路径
    /**
     * 系统默认存储
     */
    private SharedPreferences sp;
    /**
     * 任务包存储路径
     */
    private String root;
    private String taskName;
    private String dbPath;

    private String tableName = "PHOTO";


    private DBManagerUtil dbManagerUtil;
    private PhotoUtil photoUtil;

    /**
     * 1--任务包 2--村 3--样方
     */
    private int type = 3; // 1--任务包 2--村 3--样方

    /**
     * 0- 来自地块选择页面  1- 来自样方图纸拍摄类别页面
     */
    private int from = 0;


    /**
     * 位置信息是否保存
     */
    private boolean flag = false;

    private String YFBHU;
    private String MYBZ;

    private String CUNDM;
    private String CUNMING;
    private String dcqb;

    private String period;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_tz_grid);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    private String getPosition() {
        String pos = "";
        if (datas.size() > 0) {
            pos = datas.get(0).get("备注");
        }
        MYBZ = pos;
        if (StringUtil.isNotEmpty(pos)) {
            flag = true;
        }
        return pos;
    }

    private void setColunm() {
        if (imageInfoList.size() > 1) {
            gridView.setNumColumns(2);
        } else {
            gridView.setNumColumns(1);
        }
    }

    private void positionVisible() {
        if (imageInfoList.size() > 0) {
            positionLayout.setVisibility(View.VISIBLE);
        } else {
            position.setText("");
            MYBZ = "";
            flag = false;
            positionLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        taskName = getIntent().getStringExtra("taskName");
        dbPath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";
        period = getIntent().getStringExtra("period");
        period = period.contains("早稻面积") ? "春播面积" : period;
        dcqb = period + "-" + "遥感面积调查表";
        dbManagerUtil = DBManagerUtil.getInstance(dbPath, this);
        String titleTxt = "图纸拍摄";
        from = getIntent().getIntExtra("from", 0);
        if (from == 0) {
            CUNMING = Constants.selects.get(0).get("CUNMC");
            CUNDM = Constants.selects.get(0).get("CUNDM");
            YFBHU = Constants.select.get("YFBHU");
            String yfbh = getIntent().getStringExtra("yfbh");
            titleTxt = CUNMING + "样方" + yfbh + titleTxt;
        } else {
            CUNMING = Constants.tzps_parent.get("CUNMC");
            CUNDM = Constants.tzps_parent.get("CUNDM");
            YFBHU = Constants.select.get("YFBHU");
            titleTxt = CUNMING + "样方" + Constants.select.get("YFBH") + titleTxt;
        }
        setTitle(titleTxt);
        initPhoto();
        positionLayout = (LinearLayout) main.findViewById(R.id.yf_position_layout);
        position = (EditText) main.findViewById(R.id.yf_position);
        saveBtn = (Button) main.findViewById(R.id.save_btn);

        saveBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String pos = position.getText().toString().trim();
                if (StringUtil.isNotEmpty(pos)) {
                    dbManagerUtil.updateYFPosition(tableName, dbPath, pos, YFBHU, dcqb, String.valueOf(type));
                    flag = true;
                    MYBZ = pos;
                    CommenUtil.toast("保存成功", YFTZPhotoActivity.this);
                } else {
                    CommenUtil.toast("请先填写 样方位置描述", YFTZPhotoActivity.this);
                }
            }
        });

        title = (TextView) findViewById(R.id.title_textview);
        gridView = (GridView) main.findViewById(R.id.photo_grid);
        camera = (LinearLayout) main.findViewById(R.id.opreate_layout);
        btn = (ToggleButton) main.findViewById(R.id.edit_btn);

        String subtitle = "图纸照片";

        title.setText(subtitle);

        initDatas();
        position.setText(getPosition());

        camera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String pos = position.getText().toString().trim();
                // 当拍摄了一张 且 没有 保存 位置的时候
                if (imageInfoList.size() == 1 && StringUtil.isEmpty(pos) && !flag) {
                    CommenUtil.toast("请先保存 样方位置描述", YFTZPhotoActivity.this);
                } else {
                    takePhoto();
                }
            }
        });

        btn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                adapter.setDeleteFlag(isChecked);
                adapter.notifyDataSetChanged();
            }
        });

        if (adapter == null) {
            adapter = new PhotoGridAdapter(this, imageInfoList);
            adapter.setImageOperate(imgOp);
            gridView.setAdapter(adapter);
        }

        btnEnable();
    }

    private void btnEnable() {
        btn.setChecked(false);
        if (imageInfoList.size() > 0) {
            btn.setEnabled(true);
        } else {
            btn.setEnabled(false);
        }
    }

    PhotoGridAdapter.ImageOperate imgOp = new PhotoGridAdapter.ImageOperate() {

        @Override
        public void OnShow(int position, View view) {
            String path = imageInfoList.get(position).getAbsolutePath();
            if (StringUtil.isNotEmpty(path)) {
                File file = new File(path);
                if (file.exists()) {
                    ZoomImagePoup zp = new ZoomImagePoup(YFTZPhotoActivity.this);
                    zp.show(view, path, photoUtil);
                } else {
                    CommenUtil.toast("图片不存在!", YFTZPhotoActivity.this);
                }
            } else {
                CommenUtil.toast("图片路径为空!", YFTZPhotoActivity.this);
            }
        }

        @Override
        public void OnDelete(int position) {
            String rowid = datas.get(position).get("rowid");
            String path = imageInfoList.get(position).getAbsolutePath();

            boolean flag = dbManagerUtil.deleteById(tableName, "rowid", rowid, dbPath);
            if (flag) {
                photoUtil.deleteAttachmentFile(path);
                datas.remove(position);
                imageInfoList.remove(position);
                setColunm();
                adapter.notifyDataSetChanged();

                positionVisible();
                btnEnable();

                adapter.clearMemory();

                Constants.data_refresh = true;
            } else {
                CommenUtil.toast("删除失败", YFTZPhotoActivity.this);
            }
        }

    };

    private List<String> keys = new ArrayList<String>();
    private List<Map<String, String>> datas;

    private void initDatas() {
        if (keys.size() == 0) {
            keys.add("FILENAME");
            keys.add("LON");
            keys.add("LAT");
            keys.add("DATE");
            keys.add("村级行政区名称");
            keys.add("样方编号");
            keys.add("自然地块编号");
            keys.add("主要地物");
            keys.add("备注");
            keys.add("DCQB");
            keys.add("TYPE");
            keys.add("COUNTY");
        }

        String where = "DCQB = '" + dcqb + "' and TYPE = '" + type + "'";
        String val = YFBHU;
        datas = dbManagerUtil.getYFImageListData(tableName, keys, "样方编号", val, where, dbPath);

        imageInfoList.clear();
        if (datas != null && datas.size() > 0) {
            for (Map<String, String> map : datas) {
                String photoname = map.get("FILENAME");

                String path = photoUtil.getSavePath(photoname);

                ImageInfoBean im = new ImageInfoBean(photoname.replace(".jpg", ""), path, path);

                imageInfoList.add(im);
            }
            positionLayout.setVisibility(View.VISIBLE);
        } else {
            positionLayout.setVisibility(View.GONE);
        }

        setColunm();
    }

    // -------------------拍照-------------------------
    private final static int CAMERA_RESULT = 800;

    private void initPhoto() {
        String photopath = root + "/" + taskName + "/SYSTEM/images/tuzhi/" + dcqb;

        photopath += "/" + CUNMING + "/" + YFBHU;

        photoUtil = new PhotoUtil(this);
        photoUtil.setFilePath(photopath);
    }

    private void takePhoto() {
        String photoName = "";
        photoName = FileUtil.getPhotoFileName(".jpg");
        String path = photoUtil.getSavePath(photoName);
        photoUtil.takePhoto(path);
    }

    /**
     * 处理图片名称
     */
    private String imageName() {
        String name = YFBHU + "抽样调查图纸";
        if (imageInfoList.size() == 0) {
            name += "_1";
        } else {
            // 获取所有的名称
            String num = getImageNum();
            name += "_" + num;
        }

        return name;
    }

    /**
     * 获取图纸序号
     */
    private String getImageNum() {
        int n = 0;

        String filter = " 样方编号  = '" + YFBHU + "' and DCQB = '" + dcqb + "' and TYPE = '" + type + "'";
        List<String> names = dbManagerUtil.getImageNameList(dbPath, tableName, filter);

        String str = "";
        int[] arr = new int[names.size()];
        for (int i = 0; i < names.size(); i++) {
            String s = names.get(i);
            String l = s.substring(s.indexOf("_") + 1);
            str += l + ",";
            arr[i] = Integer.valueOf(l);
        }
        Arrays.sort(arr);
        int big = arr[arr.length - 1];

        if (big == arr.length) {
            n = big + 1;
        } else {

            for (int i = 0; i < big; i++) {
                if (!str.contains(String.valueOf(i + 1) + ",")) {
                    n = i + 1;
                    break;
                }
            }
        }
        return String.valueOf(n);

    }

    /**
     * 拍照返回结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_RESULT) {
            if (photoUtil.getPhotoSize(photoUtil.mPhotoPath) == 0) {// 文件内容为空
                photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
            } else {
                String imageName = imageName();
                savePhoto(imageName, "");

            }
        }
    }

    /**
     * 保存照片
     */
    private void savePhoto(String imageName, String beizhu) {
        Dialog dialog = MyLoadingDialog.createLoadingDialog(YFTZPhotoActivity.this, "正在处理照片，请稍后...");
        dialog.show();

        String date = photoUtil.getCurrTime("yyyy-MM-dd");
        String location = CommenUtil.getLatLon();// 获取当前地址经纬度
        String lat = "", lon = "";
        if (StringUtil.isNotEmpty(location)) {
            lat = location.split(",")[0];
            lon = location.split(",")[1];
        }
        // 处理图片旋转
        int degree = photoUtil.getRotate(photoUtil.mPhotoPath);
        if (degree != 0) {
            photoUtil.rotateBitmap(photoUtil.mPhotoPath, degree);
        }
        // 处理水印
        String mark = imageName + ",日期：" + date;
        mark += "," + "样方编号：" + YFBHU;

        Bitmap bitmap = photoUtil.doPhoto(photoUtil.mPhotoPath, mark);
        if (bitmap != null) {
            photoUtil.renameFile(photoUtil.mPhotoPath, imageName);

            saveToDB(imageName, lon, lat, date);

            initDatas();
            adapter.clearMemory();
            adapter.notifyDataSetChanged();

            btnEnable();
            System.out.println("拍照成功--保存到数据库");
        } else {
            photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
        }

        dialog.dismiss();
    }

    /**
     * 保存到数据库
     */
    public void saveToDB(String value, String lon, String lat, String date) {

        String pid = "_" + photoUtil.getCurrTime(null);
        pid = YFBHU + pid;

        String pkg = taskName;
        String cun = CUNMING;
        String yfbh = YFBHU;
        String uuid = YFBHU;
        String puuid = CUNDM;
        String level = "002";

        Map<String, String> map = new HashMap<String, String>();
        map.put("PHOTOID", pid);
        map.put("FILENAME", value + ".jpg");
        map.put("LON", lon);
        map.put("LAT", lat);
        map.put("DATE", date);

        map.put("村级行政区名称", cun);
        map.put("样方编号", yfbh);

        map.put("自然地块编号", "");
        map.put("主要地物", "");
        map.put("DCQB", dcqb);
        map.put("TYPE", String.valueOf(type));
        map.put("COUNTY", pkg);
        map.put("备注", MYBZ);

        dbManagerUtil.add(map, keys, tableName, "", dbPath);

        Constants.data_refresh = true;

        // 保存进度记录
        RecordDBManager rcdDB = new RecordDBManager(YFTZPhotoActivity.this);
        rcdDB.add(uuid, puuid, "2", level);

    }

    // -------------------拍照【完】--------------------

    private void isAlertDialog(final Activity activity, String str, String right, String left) {
        final AlertDialog alertDialog = new AlertDialog(activity, str, right, left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

            @Override
            public void doConfirm() {
                alertDialog.dismiss();
                YFTZPhotoActivity.this.finish();
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }
        });
    }

    private void goback() {
        if (imageInfoList.size() > 0) {
            if (flag) {
                finish();
                overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
            } else {
                CommenUtil.toast("请先保存 样方位置描述", this);
            }
        } else {
            isAlertDialog(this, "图纸照片没有拍摄，是否退出？", "退出", "继续拍照");
        }
    }

    @Override
    protected void setToolBarNavigationIcon(Toolbar toolbar) {
        super.setToolBarNavigationIcon(toolbar);
    }

    @Override
    public void setmOnBackClickListener(onBackClickListener mOnBackClickListener) {
        mOnBackClickListener = new onBackClickListener() {
            @Override
            public void onBackClick() {
                goback();
            }
        };
        super.setmOnBackClickListener(mOnBackClickListener);

    }
}
